package servlet;

import dao.ArticleDao;
import dao.daoimpl.ArticleDaoImpl;
import bean.Collection;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet(name="PaginateServlet",urlPatterns = "/PaginateServlet")
public class PaginateServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        User user=(User)request.getSession().getAttribute("user");
        int p=Integer.parseInt(request.getParameter("changePage"));
        int cnt=(int)request.getSession().getAttribute("cnt");
        int page=(int)request.getSession().getAttribute("page");
        ArrayList<Collection> collections=(ArrayList<Collection>)request.getSession().getAttribute("userCollected");
        ArticleDao articleDao=new ArticleDaoImpl();
        try {
            if(p<page){
                request.getSession().setAttribute("userPaginate", articleDao.getPaginateArticle(cnt-3, 3, user));
                request.getSession().setAttribute("cnt", cnt-3);
                request.getSession().setAttribute("page",p);
            }else if(p>page){
                request.getSession().setAttribute("userPaginate", articleDao.getPaginateArticle(cnt+3, 3, user));
                request.getSession().setAttribute("cnt", cnt+3);
                request.getSession().setAttribute("page",p);
            }else{
                request.getSession().setAttribute("userPaginate", articleDao.getPaginateArticle(cnt, 3, user));
                request.getSession().setAttribute("page", cnt);
                request.getSession().setAttribute("page",p);
            }
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }
}
